package com.yc.vote.servlet;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",
        urlPatterns = {"/add.html","/vote.html"})
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println("=========== LoginFilter init ===================");
    }

    public void destroy() {
        System.out.println("=========== LoginFilter destroy ===================");
    }

    @Override
    public void doFilter(
            ServletRequest request,
            ServletResponse response,
            FilterChain chain) throws ServletException, IOException {
        System.out.println("=========== LoginFilter doFilter ===================");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 判断登录
        if(req.getSession().getAttribute("myinfo")==null){
            resp.sendRedirect("login.html");
            return;
        }
        // chain.doFilter  放行 => 请求到达目标资源 或者 下一个过滤
        chain.doFilter(request, response);
    }
}
